package com.zhuangjie.rider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaungjie.base.utils.PropertiesCopyUtils.PropertiesCopy;
import com.zhuangjie.mvc.enhance.mp_query_enhance.LambdaQueryWrapperPlus;
import com.zhuangjie.mvc.enhance.mp_query_enhance.LambdaQueryWrapperPlusHelper;
import com.zhuangjie.rider.dto.RiderEvaluateDTO;
import com.zhuangjie.rider.entity.DeliveryOrder;
import com.zhuangjie.rider.entity.RiderEvaluate;
import com.zhuangjie.rider.mapper.RiderEvaluateMapper;
import com.zhuangjie.rider.service.DeliveryOrderService;
import com.zhuangjie.rider.service.RiderEvaluateService;
import com.zhuangjie.security.provider.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 骑手评价 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2024-04-25
 */
@Service
public class RiderEvaluateServiceImpl extends ServiceImpl<RiderEvaluateMapper, RiderEvaluate> implements RiderEvaluateService {

    @Autowired
    private DeliveryOrderService deliveryorderService;

    @Override
    public void submitEvaluate(RiderEvaluateDTO riderEvaluateDTO) {
        RiderEvaluate deliveyOrderForRiderEvaluate = LambdaQueryWrapperPlusHelper
                .queryOne(new LambdaQueryWrapperPlus<>(DeliveryOrder.class, RiderEvaluate.class)
                        .eq(DeliveryOrder::getOrderId, riderEvaluateDTO.getOrderId()), deliveryorderService::getOne
                );
        if (deliveyOrderForRiderEvaluate == null) {
            throw new RuntimeException("评价骑手但无法确认配送订单！");
        }
        RiderEvaluate riderEvaluate = PropertiesCopy.type(RiderEvaluateDTO.class, RiderEvaluate.class).produce(riderEvaluateDTO);
        Long riderId = deliveyOrderForRiderEvaluate.getRiderId();
        if (riderId == null) {
            throw new RuntimeException("评价骑手但无法确认骑手！");
        }
        riderEvaluate.setRiderId(riderId);
        Long evaluateUserId = UserProvider.currentUserId();
        riderEvaluate.setUserId(evaluateUserId);
        // 看看是否已经评价过
        if (this.count(Wrappers.lambdaQuery(RiderEvaluate.class)
                .eq(RiderEvaluate::getOrderId, riderEvaluateDTO.getOrderId())) > 0) {
            throw new RuntimeException("已经评价过，不能重复评价！");
        }
        // 保存
        if (!this.save(riderEvaluate)) {
            throw new RuntimeException("保存骑手评价失败！");
        }
    }
}
